// 封装请求
import { Base } from "../config/config";
const request = (options) => {
    let data = options.data || {}
    const query = options.query || false
    let params = {}
    for (let key in data) {
        if (data[key] === 0) {
            params[key] = data[key]
        } else {
            if (data[key]) {
                params[key] = data[key]
            }
        }
    }
    if (query) {
        let parameter = Object.keys(params).map(key => key + "=" + params[key]).join("&");
        options.url = `${options.url}?${parameter}`
    }

    // return new Primise才可以使用then或者async 
    return new Promise(function (resolve, reject) {

        if (options.data) {
            Object.keys(options.data).map((item) => {
                if (options.data[item] == '' || options.data[item] == null) {
                    delete options.data[item]
                }
            })
        }

        let header = options.header ? {
            ...options.header,
            'token': wx.getStorageSync('token') ||
                ''
        } : {
                'Content-type': 'application/json;charset=UTF-8',
                'token': wx.getStorageSync('token') ||
                    ''
            }
        wx.request({
            url: `${Base}${options.url}`,
            data: options.data,
            header,
            method: options.method,
            timeout: 10000,
            success: (result) => {
                // 请求成功的回调
                if (result.data.code === 0) {
                    resolve(result.data);
                } else if (result.data.code === 401) {
                    wx.clearStorage()
                    wx.clearStorageSync()
                    wx.showModal({
                        title: '提示',
                        content: '登录已过期,请重新登录',
                        success(res) {
                            if (res.confirm) {
                                wx.switchTab({
                                    url: '/pages/individual/individual'
                                })
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                    reject(err)
                } else {
                    wx.showToast({
                        title: result.data.msg,
                        icon: 'none',
                        duration: 3000
                    })
                    reject(err)
                }

            },
            fail: (err) => {
                // 请求失败的回调
                wx.showToast({
                    title: '网络连接失败',
                    icon: 'none',
                    duration: 3000
                })
                //请求失败
                reject(err)
            }
        })
    })

}
export { request } 